package ch.wsl.postgres2mapperdao.common

/**
 * 
 * Postgres2mapperdao
 * 
 * @author Andrea Minetti
 *
 * 21 Sep 2012
 * 
 */

import java.util.Properties
import com.googlecode.mapperdao.utils.Setup
import com.googlecode.mapperdao._
import com.googlecode.mapperdao.SimpleEntity
import com.googlecode.mapperdao.jdbc.Jdbc
import org.springframework.transaction.PlatformTransactionManager
import org.apache.commons.dbcp.BasicDataSourceFactory

object DatabaseConnection {

		

        //logger.debug("Configuring mapperdao")
        
        var entities = List[Entity[_,_]]()
		var jdbc: Jdbc = null
		var mapperDao: MapperDao = null
		var queryDao: QueryDao = null
		var txManager: PlatformTransactionManager = null
        
        def register(entity: Entity[_,_]) = {
		  entities = entities ::: List(entity)
		}
		
		def connect(user: String, password: String, db: String) = {
			println("Connecting to database")
	        val properties = new Properties
	        //properties.load(getClass.getResourceAsStream("/database.properties"))
	        properties.setProperty("driverClassName","org.postgresql.Driver")
	        properties.setProperty("url","jdbc:postgresql://localhost/"+db)
	        properties.setProperty("username",user)
	        properties.setProperty("password",password)
	
	        val dataSource = BasicDataSourceFactory.createDataSource(properties)
		    val (jdbc2, mapperDao2, queryDao2, txManager2) = Setup.postGreSql(dataSource,entities)
		    jdbc = jdbc2
		    mapperDao = mapperDao2
		    queryDao = queryDao2
		    txManager= txManager2
		    
		}
  
}